<!--条码信息弹窗-->
<template>
  <el-dialog
    title="条码信息"
    v-if="barCodeDialogVisible"
    :visible.sync="barCodeDialogVisible"
    width="65%"
    :before-close="barCodeClose"
    v-dialogDrag
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :inline-message="true"
    class="m-barcodeInfo-dialog"
  >
    <div>
      <el-form
        ref="codeForm"
        label-width="70px"
        class="demo-ruleForm"
        :inline-message="true"
      >
        <el-row :gutter="10" class="m-condition">
          <el-col :span="8">
            <el-form-item label="条码">
              <el-input
                v-model="barCode"
                placeholder="请输入条码"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="生产批号">
              <el-input
                v-model="codeForm.batchCode"
                placeholder="请输入生产批号"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="9">
            <el-form-item label="生产日期">
              <el-date-picker
                v-model="codeForm.produceDate"
                type="date"
                placeholder="请选择生产日期"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="8" v-if="!isSmallCode">
            <el-form-item label="送货单号">
              <el-input
                v-model="codeForm.deliveryNo"
                placeholder="请输入送货单号"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="打印状态">
              <el-select
                value-key="id"
                v-model="printCode"
                placeholder="打印状态"
              >
                <el-option
                  v-for="item in printState"
                  :key="item.id"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="2" v-if="delCodeShow" class="m-floatright">
            <el-button type="primary" @click="delCode" :disabled="codeDeling"
              >删除</el-button
            >
          </el-col>
          <el-col :span="3" class="m-floatright">
            <el-button
              type="primary"
              @click="printBarcode(2)"
              :disabled="printDis"
              >预览打印</el-button
            >
          </el-col>
          <el-col :span="2" class="m-floatright">
            <el-button
              type="primary"
              @click="printBarcode(1)"
              :disabled="printDis"
              >打印</el-button
            >
          </el-col>
          <el-col :span="2" class="m-floatright">
            <el-button
              type="primary"
              @click="orderRowSelected(mainParams.data, 2)"
              :disabled="printDis"
              >查询</el-button
            >
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="m-agTableModel">
      <agGridComponents
        ref="barCodeGridComponent"
        :getGridOptions="barCodeGridOptions"
        :getColumnDefs="barCodeColumnDefs"
        :getRowSelection="'multiple'"
      ></agGridComponents>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-pagination
        @size-change="barCodeHandleSizeChange"
        @current-change="barCodeHandleCurrentChange"
        @prev-click="barCodeHandlePrevClick"
        @next-click="barCodeHandleNextClick"
        :current-page="pageInfo.current"
        :page-sizes="[100, 200, 500, 1000]"
        :page-size="pageInfo.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageInfo.total"
        :pager-count="5"
      ></el-pagination>
    </div>
  </el-dialog>
</template>

<script>
import _Api from "@/api";
import agGridComponents from "@/components/agGridComponents.js";
import waterfall from "async-es/waterfall";
import fileStream from "@/public/fileStream.js";
import { startPrint } from "lesso-common/webprint";
import constant from "@/public/constant";
import apienv from "@/api/env";
import Msg from "@/public/message";

const ENV = apienv[constant.appenv];

export default {
  data() {
    return {
      //   查询条件
      codeForm: {
        deliveryNo: "",
        produceDate: "",
        batchCode: "",
      },
      //   打印状态
      printCode: "",
      //   条码
      barCode: "",
      printDis: false,
      //   分页相关
      pageInfo: {
        size: 100,
        current: 1,
        total: 0,
      },
      //   表格配置
      barCodeGridOptions: {},
      //   表格列配置
      barCodeColumnDefs: [],
      //   是否打印
      messageType: "",
      codeDeling: false,
      printState: [
        { label: "未打印", value: 1 },
        { label: "已打印", value: 2 },
      ],
      barcodeArr: [],
    };
  },
  props: {
    barCodeDialogVisible: {
      type: Boolean,
    },
    isSmallCode: {
      type: Boolean,
    },
    mainParams: {
      type: Object,
    },
    delCodeShow: {
      type: Boolean,
    },
    supplierInfo: {
      type: Array,
    },
    showAddCodeCol: {
      type: Boolean,
      default: false,
    },
  },
  methods: {
    barCodeClose() {
      this.$emit("barCodeClose");
    },
    barCodeHandleSizeChange(val) {
      this.pageInfo.size = val;
      this.orderRowSelected(this.mainParams.data, 3);
    },
    barCodeHandleCurrentChange(val) {
      this.pageInfo.current = val;
      this.orderRowSelected(this.mainParams.data, 3);
    },
    barCodeHandlePrevClick(val) {
      this.pageInfo.current = val;
      this.orderRowSelected(this.mainParams.data, 3);
    },
    barCodeHandleNextClick(val) {
      this.pageInfo.current = val;
      this.orderRowSelected(this.mainParams.data, 3);
    },
    orderRowSelected(params, selectSign) {
      let that = this;
      let codeMxType = "";
      let codeUnique = "";
      if (selectSign === 2) {
        this.pageInfo.current = 1;
      }
      this.$refs.barCodeGridComponent.loading = true;
      if (that.isSmallCode) {
        codeMxType = 2;
        codeUnique = params.uniqueSmall;
      } else {
        codeMxType = 1;
        codeUnique = params.unique;
      }
      let obj = {
        ...this.codeForm,
        unique: codeUnique,
        currentPage: this.pageInfo.current - 1,
        pageSize: this.pageInfo.size,
        type: codeMxType,
      };
      if (this.barCode != "") obj.barcode = this.barCode;
      if (this.printCode != "" && this.printCode != null)
        obj.isPrint = this.printCode - 1;

      _Api
        .getBarCodes(obj)
        .then(function(response) {
          let data = response.data;
          that.$refs.barCodeGridComponent.loading = false;
          if (data.code == "1") {
            if (data.total > 0) {
              that.$refs.barCodeGridComponent.gridOptions.api.setRowData(
                data.rows.splice(0)
              );
              if (that.isSmallCode) {
                that.$refs.barCodeGridComponent.gridOptions.columnApi.setColumnVisible(
                  "delivery",
                  false
                );
              }
              that.$refs.barCodeGridComponent.rowDataChange = true;
              that.$refs.barCodeGridComponent.gridOptions.api.forEachNode(
                function(node) {
                  let rowIndex = that.$refs.barCodeGridComponent.gridOptions.api.getRowNode(
                    node.rowIndex
                  );
                  if (node.data.printTime === "0")
                    rowIndex.setDataValue("printTime", 0);
                  else
                    rowIndex.setDataValue(
                      "printTime",
                      parseInt(node.data.printTime)
                    );
                }
              );
              that.pageInfo.total = data.total;
            } else {
              that.pageInfo.total = 0;
              that.$refs.barCodeGridComponent.gridOptions.api.setRowData([]);
            }
          } else {
            that.$refs.barCodeGridComponent.loading = false;
            that.pageInfo.total = 0;
            that.$alert(data.info, {
              showClose: false,
              confirmButton: "确定",
              customClass: "alertFailure",
            });
          }
        })
        .catch((err) => {
          that.$refs.barCodeGridComponent.loading = false;
          that.pageInfo.total = 0;
          that.$alert(err.data.message, {
            showClose: false,
            confirmButton: "确定",
            customClass: "alertFailure",
          });
        });
    },
    delCode() {
      let delRows = this.$refs.barCodeGridComponent.gridOptions.api.getSelectedRows();
      let that = this;
      if (delRows.length <= 0) {
        this.$alert("提示：请选择需要删除的数据", {
          showClose: false,
          confirmButtonText: "确定",
          customClass: "alertPrompt",
        });
        return;
      }
      let codeList = [];
      let purOrdNoList = [];
      let codeType = "";
      let isSave = 0;
      let tempCode = 0;
      delRows.forEach((item) => {
        if (item.delivery != "") {
          isSave = isSave + 1;
        }

        codeList[tempCode] = item.id + "," + item.barcode;
        purOrdNoList[tempCode] = item.purOrdNo + "," + item.purOrdMxNo;
        tempCode = tempCode + 1;
      });

      if (this.isSmallCode) {
        codeType = 2;
      } else {
        codeType = 1;
      }

      if (isSave !== 0) {
        this.$alert("提示：部分防伪码已进行扫码并且保存确认，无法删除！", {
          showClose: false,
          confirmButtonText: "确定",
          customClass: "alertPrompt",
        });
        return;
      }

      let obj = {
        operatorName: constant.userName,
        barcodes: codeList,
        purOrds: purOrdNoList,
        type: codeType,
      };
      this.codeDeling = true;
      _Api
        .delBarCode(obj)
        .then(function(response) {
          let data = response.data;
          if (data.code == "1") {
            that.codeDeling = false;
            that.orderRowSelected(that.mainParams.data, 3);
            that.$emit("updateBarcode");
            that.$message({
              message: "删除防伪码成功！",
              type: "success",
            });
          } else {
            that.codeDeling = false;
            that.$alert("操作失败！" + data.info, {
              showClose: false,
              confirmButton: "确定",
              customClass: "alertFailure",
            });
          }
        })
        .catch((err) => {
          that.codeDeling = false;
          Msg.showErrorMsg(err.data.message);
        });
    },
    print(type) {
      let that = this;
      let printWay = "";
      let printId = "";
      let printKey = "";
      let tempArr = [];
      let rows = this.$refs.barCodeGridComponent.gridOptions.api.getSelectedRows();
      if (rows.length <= 0) {
        this.$alert("提示：请选择需要打印的数据", {
          showClose: false,
          confirmButtonText: "确定",
          customClass: "alertPrompt",
        });
        return;
      }

      if (this.isSmallCode == true) {
        printWay = 2;
      } else if (this.isSmallCode == false) {
        printWay = 1;
      }
      rows.forEach((item) => {
        let codeObj = {
          barcode2: item.barcode,
          produceNo: item.batchCode,
          produceDate: item.produceDate,
          qualityNo: item.inspectionCode,
          shortCode:
            item.barcode.substring(0, 4) +
            "-" +
            item.barcode.substring(
              item.barcode.length - 4,
              item.barcode.length
            ),
          barcode: constant.barCodePrex + item.barcode,
        };
        tempArr.push(codeObj);
      });
      this.barcodeArr = tempArr;
      let paramsTemp = {
        barcodes: tempArr,
        supplierCode: this.supplierInfo[0].supplierCode,
        matCode: rows[0].matCode,
        type: rows[0].type,
      };

      _Api
        .saveWebCodeInfo(paramsTemp)
        .then(function(response) {
          let data = response.data;
          if (data.code == "1") {
            let tempCodeInfo = data.rows;
            printId = tempCodeInfo.id;
            printKey = tempCodeInfo.key;
            if (type === 1) {
              // that.updatePrintCount();
              fileStream
                .getFileInfo(printKey)
                .then((data) => {
                  startPrint({
                    basicUrl: ENV["srm"], //权限接口地址
                    reportUrl: `${ENV["srm"]}download2?viewPath=${
                      data.url
                    }&groupName=${data.groupName}`, //打印模板地址
                    dataUrl: "ralOrderBarcode/barcodeInfoToMap", //数据接口地址
                    params: {
                      token: "",
                      id: printId,
                      supplierCode: that.supplierInfo[0].supplierCode,
                      matCode: rows[0].matCode,
                      type: printWay,
                    }, //参数对象
                    printType: "print", // 打印方式print直接打印，preview先预览
                    storage: that.resetSetItem,
                  });
                })
                .catch((err) => {
                  that.$alert(err, {
                    showClose: false,
                    confirmButton: "确定",
                    customClass: "alertFailure",
                  });
                });
            } else {
              fileStream
                .getFileInfo(printKey)
                .then((data) => {
                  startPrint({
                    basicUrl: ENV["srm"], //权限接口地址
                    reportUrl: `${ENV["srm"]}download2?viewPath=${
                      data.url
                    }&groupName=${data.groupName}`, //打印模板地址
                    dataUrl: "ralOrderBarcode/barcodeInfoToMap", //数据接口地址
                    params: {
                      token: "",
                      id: printId,
                      supplierCode: that.supplierInfo[0].supplierCode,
                      matCode: rows[0].matCode,
                      type: printWay,
                    }, //参数对象
                    printType: "preview", // 打印方式print直接打印，preview先预览
                    storage: that.resetSetItem,
                  });
                })
                .catch((err) => {
                  that.$alert(err, {
                    showClose: false,
                    confirmButton: "确定",
                    customClass: "alertFailure",
                  });
                });
            }
          } else {
            Msg.showErrorMsg("操作失败");
          }
        })
        .catch((err) => {
          Msg.showErrorMsg(err.data.message);
        });
    },
    printPc(type) {
      let that = this;
      let tempArr = [];
      let rows = this.$refs.barCodeGridComponent.gridOptions.api.getSelectedRows();
      let printMBMC = ""; //打印条码类型
      if (rows.length <= 0) {
        this.$alert("提示：请选择需要打印的数据", {
          showClose: false,
          confirmButtonText: "确定",
          customClass: "alertPrompt",
        });
        return;
      }
      let codeObj = {
        supplierCode: this.supplierInfo[0].supplierCode,
        matCode: rows[0].matCode,
        type: this.isSmallCode == true ? 2 : 1,
      };
      const switchTemplates = ['painBarcode_1', 'painBarcode_2', 'painBarcode_3', 'painBarcode_4'];
      //获取打印数据
      _Api.getCodePrintData(codeObj).then(function(response) {
        let data = response.data;
        // 此处需考虑是否做字段兼容处理
        if (data.code == "1") {
          let codeHeader = data.rows.unitedLabelInfo;
          rows.forEach((item) => {
            let obj = {};
            obj.weight = codeHeader.weight; //净重
            obj.shelfLife = codeHeader.shelfLife; //保质期
            obj.model = codeHeader.model; //型号
            obj.execStandard = codeHeader.standard; //执行标准
            obj.produceLocation = codeHeader.productionArea; //产地
            obj.prodName = codeHeader.labMatName;         // 产品名称
            obj.matching = codeHeader.matching;           // 配比
            obj.produceDate = item.produceDate; //生产日期
            obj.barcode = constant.barCodePrex + item.barcode; //带地址的条码
            obj.barcode2 = item.barcode; //条码号
            obj.produceNo = item.batchCode; //生产批号
            obj.qualityNo = item.inspectionCode; //质检号
            obj.pigments = codeHeader.pigments; //颜色

            obj.bulk = codeHeader.bulk;         // 体积
            obj.fileUrl = codeHeader.fileUrl;   // 产品图片图
            obj.auxAmount = codeHeader.auxAmount;   // 产品总数量
            obj.spec = codeHeader.spec;   // 产品规格
            obj.num1 = codeHeader.num1;   // 产品规格


            obj.shortCode =
              item.barcode.substring(0, 4) +
              "-" +
              item.barcode.substring(
                item.barcode.length - 4,
                item.barcode.length
              );
            tempArr.push(obj);
          });

          if (codeHeader.templateCode == "paintBarcode") {
            //  大码
            printMBMC = "paintBarcode_pc";
          } else if (codeHeader.templateCode == "paintBarcode_1") {
            // 小码
            printMBMC = "paintBarcode_1_pc";
          } else if (codeHeader.templateCode == "paintBarcode_2") {
            printMBMC = "paintBarcode_2_pc";
            // 开关类产品的模板编号直接用接口返回的模板编号，无需映射
          } else if(switchTemplates.indexOf(codeHeader.templateCode) != -1) {
            printMBMC = codeHeader.templateCode;
          } else {
            //  默认大码
            printMBMC = "paintBarcode_pc";
          }
          if (type === 1) {
            if (constant.printType == "local") {
              ipcRenderer.send("IPCR_M_PRINTLOCAL", {
                type: printMBMC,
                rows: tempArr,
                optype: "pp",
                isdefaultp: 1, //控制是否直接打印,0为选择打印、1为直接打印
              });
              that.updatePrintCount();
            } else {
              fileStream
                .getFileInfo(printMBMC)
                .then((data) => {
                  ipcRenderer.send("IPCR_M_PRINT", {
                    type: printMBMC,
                    rows: tempArr,
                    groupName: data.groupName,
                    optype: "pp",
                    url: data.url,
                    isdefaultp: 1, //控制是否直接打印,0为选择打印、1为直接打印
                  });
                  that.updatePrintCount();
                })
                .catch((err) => {
                  that.$alert(err, {
                    showClose: false,
                    confirmButton: "确定",
                    customClass: "alertFailure",
                  });
                });
            }
          } else {
            if (constant.printType == "local") {
              ipcRenderer.send("IPCR_M_PRINTLOCAL", {
                type: printMBMC,
                rows: tempArr,
                optype: "pr",
                isdefaultp: 1, //控制是否直接打印
              });
            } else {
              fileStream
                .getFileInfo(printMBMC)
                .then((data) => {
                  ipcRenderer.send("IPCR_M_PRINT", {
                    type: printMBMC,
                    rows: tempArr,
                    groupName: data.groupName,
                    optype: "pr",
                    isdefaultp: 1, //控制是否直接打印
                    url: data.url,
                  });
                })
                .catch((err) => {
                  that.$alert(err, {
                    showClose: false,
                    confirmButton: "确定",
                    customClass: "alertFailure",
                  });
                });
            }
          }
        }
      });
    },
    printBarcode(type) {
        if (constant.userAgent == 'web') {
          this.print(type);
        } else {
          this.printPc(type)
        }
    },
    // 更新打印次数
    updatePrintCount() {
      let that = this;
      waterfall([
        function sendIpcRenderer(callback) {
          if (constant.userAgent == "pc") {
            ipcRenderer.once("IPCR_M_PRINT_RES", (event, arg) => {
              callback(null, arg.printData.rows);
            });
          } else {
            callback(null, that.barcodeArr);
          }
        },
        function updatePrintTime(data, callback) {
          let obj = {};
          let temp = [];
          data.forEach((item) => {
            temp.push(item.barcode2);
          });
          obj.barcodes = temp;
          that.printDis = false;
          _Api.updatePrintTime(obj).then(function(response) {
            let data = response.data;
            if (data.code != "1") {
              that.$alert("操作失败！：更新打印次数操作失败！", {
                showClose: false,
                confirmButton: "确定",
                customClass: "alertFailure",
              });
            } else {
              that.orderRowSelected(that.mainParams.data, 3);
            }
          });
        },
      ]);
    },
    // 保存打印状态到本地存储
    savePrintState() {
      this.messageType = sessionStorage.getItem("printType");
    },
  },
  mounted() {
    this.$nextTick((_) => {
      this.orderRowSelected(this.mainParams.data, 3);
      if (this.showAddCodeCol) {
        this.$refs.barCodeGridComponent.gridOptions.columnApi.setColumnVisible(
          "applyNo",
          true
        );
      } else {
        this.$refs.barCodeGridComponent.gridOptions.columnApi.setColumnVisible(
          "applyNo",
          false
        );
      }
    });
  },
  components: {
    agGridComponents,
  },
  watch: {
    messageType: {
      handler(newName, oldName) {
        if (newName == "print") {
          this.updatePrintCount();
          this.resetSetItem("printType", "");
        }
      },
      immediate: true,
    },
  },
  beforeMount() {
    window.addEventListener("setItem", this.savePrintState);
    this.barCodeColumnDefs = [
      {
        headerName: "序号",
        field: "",
        cellRenderer: function(params) {
          return parseInt(params.node.id) + 1;
        },
        hide: true,
      },
      {
        headerName: "条码",
        field: "",
        checkboxSelection: true,
        headerCheckboxSelection: true,
        headerCheckboxSelectionFilteredOnly: true,
        cellRenderer: function(params) {
          let hideStr = params.data.barcode.substring(
            4,
            params.data.barcode.length - 4
          );
          return params.data.barcode.replace(hideStr, "**********");
        },
      },
      { headerName: "送货单号", field: "delivery" },
      {
        headerName: "生成日期",
        field: "createDate",
        cellRenderer: function(params) {
          if (params.value) return new Date(params.value).Format("yyyy-MM-dd");
        },
      },
      {
        headerName: "生产日期",
        field: "produceDate",
        cellRenderer: function(params) {
          if (params.value) return new Date(params.value).Format("yyyy-MM-dd");
        },
      },
      { headerName: "生产批号", field: "batchCode" },
      {
        headerName: "是否加码",
        field: "applyNo",
        cellRenderer: (params) => {
          if (params.value.indexOf("JM") > -1) return "<span>是</span>";
          else return "<span>否</span>";
        },
        hide: true,
      },
      {
        headerName: "打印次数",
        field: "printTime",
        filter: "agNumberColumnFilter",
      },
    ];
  },
};
</script>

<style lang="less">
.m-barcodeInfo-dialog {
  .el-form {
    .el-form-item {
      margin-bottom: 5px;
    }
  }
  .m-floatright {
    float: right;
  }
}
</style>
